import { useRef, useEffect } from 'react';
import type { MutableRefObject } from 'react';
import type { DescriptionProps, DescInstance } from './typing';

export function useDescription(
  initialProps?: Partial<DescriptionProps>
) {
  const descRef = useRef<DescInstance | null>(null);
  const isLoaded = useRef(false);
  const timerRef = useRef<NodeJS.Timeout | null>(null);

  // 注册组件实例 - 新增对null的处理
  const register = (instance: DescInstance | null) => {
    if (instance) {
      descRef.current = instance;
      isLoaded.current = true;
      // 设置初始属性
      if (initialProps) {
        instance.setDescProps(initialProps);
      }
    } else {
      // 组件卸载时清理
      descRef.current = null;
      isLoaded.current = false;
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    }
  };

  // 更新组件属性 - 增加更多安全检查
  const setDescProps = (props: Partial<DescriptionProps>) => {
    // 如果组件已卸载，直接返回
    if (!isLoaded.current) return;

    if (descRef.current) {
      descRef.current.setDescProps(props);
    } else if (!timerRef.current) {
      // 只在没有活跃定时器时创建新定时器
      timerRef.current = setTimeout(() => {
        setDescProps(props);
        timerRef.current = null;
      }, 100);
    }
  };

  // 组件卸载时清理定时器  解决跳转页面空白报错问题
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
      // 确保卸载时重置状态
      isLoaded.current = false;
      descRef.current = null;
    };
  }, []);

  return {
    register,
    setDescProps,
    descRef: descRef as MutableRefObject<DescInstance>
  };
}